/**
 * @export
 * @since 1.0.0
 * @author lsl
 * @module NavigationBar
 * @description 插件导航栏，左侧通常一个按钮，中间标题/副标题，右侧通常一到两个按钮或文字。
 * - 导航栏高度固定，不允许更改，背景色仍然可以自定义
 * @property {string} type - 导航栏类型：`NavigationBar.TYPE.DARK` 表示*深色背景白色文字*，`NavigationBar.TYPE.LIGHT` 相反
 * @property {string} buttonType - 按钮类型：`NavigationBar.BUTTONTYPE.ICON` 表示*图标按钮*，`NavigationBar.BUTTONTYPE.TEXT` 表示*文本按钮(当left/right按钮里，有设置title的，才需要设置为TEXT)*
 * @property {object} backgroundColor - 导航栏背景色
 * @property {array} left - 左侧按钮的集合，最多显示两个，多余无效 [{ source,title, disable, showDot, onPress }]
 * @property {array} right - 右侧按钮的集合，最多显示两个，多余无效 [{ source,title, disable, showDot, onPress }]
 * @property {string} title - 中间的标题
 * @property {string} subtitle - 中间的副标题
 * @property {string} onPressTitle - 点击标题的事件
 * @example
 * ```js
 * <NavigationBar
 *   backgroundColor='transparent'
 *   type={NavigationBar.TYPE.DARK}
 *   buttonType={NavigationBar.BUTTONTYPE.ICON}
 *   left={[
 *     {
 *       source: NavigationBar.ICON.BACK,
 *       onPress: _ => this.props.navigation.goBack()
 *     }
 *   ]}
 *   right={[
 *     {
 *       source: NavigationBar.ICON.SHARE,
 *       disable: true,
 *       onPress: _ => console.log('onPress')
 *     },
 *     {
 *       source: NavigationBar.ICON.MORE,
 *       showDot: this.state.showDot,
 *       onPress: _ => console.log('onPress')
 *     }
 *   ]}
 *   title='标题'
 *   subtitle='副标题'
 *   onPressTitle={_ => console.log('onPressTitle')}
 * />
 * ```
 * @see com.xiaomi.demo->教程->NavigationBarDemo
 */
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Dimensions, Image, Platform, StatusBar, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-navigation';
/**
 * 导航栏类型
 */
const TYPE = {
    /**
     * 深色背景
     */
    DARK: 'dark',
    /**
     * 浅色背景
     */
    LIGHT: 'light'
}
Object.freeze(TYPE);

/**
 * 按钮类型
 */
const BUTTONTYPE = {
    /**
     * 图标，left\right数组长度最大限制为2，宽度较小
     */
    ICON: 'icon',
    /**
     * 文本,left\right数组长度最大限制为1，但是宽度较大
     */
    TEXT: 'text'
}
Object.freeze(BUTTONTYPE);
/**
 * 图标资源的索引
 */
const ICON = {
    /**
     * 返回
     */
    BACK: require('../Images//fanhui.png'),
    /**
     * 更多
     */
    MORE: require('../Images/fenlei-yixuanzhong.png'),
    /**
     * 分享
     */
    SHARE: require('../Images/xing-weixuanzhong.png'),
}
Object.freeze(ICON);

const { width } = Dimensions.get('window'); // 屏幕宽度
const navigationBarHeightThin = 44; // 导航栏高度，无副标题
const navigationBarHeightFat = 60; // 导航栏高度，有副标题
const paddingHorizontal = 16; // 导航栏左右内边距
const iconSize = 28; // 图标尺寸
const textBtnSize = 50; // 文本按钮尺寸
const lightTitleColor = '#000000'; // 浅色背景下标题颜色
const darkTitleColor = '#ffffff'; // 深色背景下标题颜色
const lightSubtitleColor = '#666666'; // 浅色背景下副标题颜色
const darkSubtitleColor = 'rgba(255,255,255,0.7)'; // 深色背景下副标题颜色
const lightBtnTextColor = "#28BECA";
const darkBtnTextColor = "#ffffff";

export default class NavigationBar extends Component {
    static propTypes = {
        type: PropTypes.oneOf([TYPE.DARK, TYPE.LIGHT]),
        buttonType: PropTypes.oneOf([BUTTONTYPE.ICON, BUTTONTYPE.TEXT]),
        backgroundColor: PropTypes.string,
        left: PropTypes.array,
        right: PropTypes.array,
        title: PropTypes.string,
        subtitle: PropTypes.string,
        onPressTitle: PropTypes.func,
        checkUpdate: PropTypes.bool
    }
    static defaultProps = {
        type: TYPE.LIGHT,
        buttonType: BUTTONTYPE.ICON,
        left: [],
        right: [],
        checkUpdate: false
    }
    static TYPE = TYPE;
    static ICON = ICON;
    static BUTTONTYPE = BUTTONTYPE;

    constructor(props, context) {
        super(props, context);
        this.state = {
            hasUpdated: false
        }
    }

    /**
     * @description 根据处理后的按钮集合数据渲染按钮
     * @param {array} arr - 经过处理后的按钮集合
     */
    renderIcons(arr, left) {
        const tiniColor = this.isDarkStyle ? darkTitleColor : lightTitleColor;
        const textColor = this.isDarkStyle ? darkBtnTextColor : lightBtnTextColor;
        const icons = this.props.buttonType == BUTTONTYPE.ICON ? (arr || []).slice(0, 2) : (arr || []).slice(0, 1); // 最多显示两个图标；最多显示一个文本按钮
        const size = this.props.buttonType == BUTTONTYPE.ICON ? iconSize : textBtnSize;
        return icons.map((icon, i) => {
            // 如果没有找过图标资源，则显示占位空白
            if (!icon.source && !icon.title) {
                return <View key={"emptyIcon" + i} style={{ width: size }} />
            }
            if (this.state.hasUpdated && icon.source == ICON.MORE) {
                icon.showDot = true;
            }

            return (
                <View
                    key={"icon" + i}
                    style={[{ width: size, height: 44, opacity: icon.disable ? 0.5 : 1, margin: 7 }, i == 0 ? { marginLeft: 0, marginRight: icons.length == 1 ? 0 : 7 } : {}, i == 1 ? { marginRight: 0 } : {}]}
                >
                    {icon.showDot
                        ? <View
                            style={[styles.dot, this.props.buttonType == BUTTONTYPE.ICON ? { right: 5, top: 5 } : icon.title ? { right: 0, top: 10 } : { right: 25, top: 5 }]}
                        />
                        : null
                    }
                    <TouchableOpacity
                        style={{ width: size, height: 44, justifyContent: "center" }}
                        disabled={icon.disable}
                        onPress={icon.onPress}
                    >
                        {
                            icon.title ? <Text style={{ color: textColor, fontSize: 15, textAlign: left ? "left" : "right" }}>
                                {icon.title}
                            </Text> : <Image
                                    style={{ width: iconSize, height: iconSize, tintColor: tiniColor }}
                                    source={icon.source}
                                />
                        }
                    </TouchableOpacity>
                </View>
            )
        })
    }
    /**
     * 中间标题部分
     */
    renderTitle() {
        const { title, onPressTitle } = this.props;
        const titleColor = {
            color: this.isDarkStyle ? darkTitleColor : lightTitleColor
        }
        return (
            <View style={[styles.titleContainer]}>
                <Text
                    numberOfLines={1}
                    style={[styles.title, titleColor]}
                    onPress={onPressTitle}
                >
                    {title || ''}
                </Text>
            </View>
        )
    }
    /**
     * 导航栏在进入插件的时候就已经生成，并且常驻，所以样式判断逻辑不能写在 constructor 中
     */
    render() {
        this.isDarkStyle = this.props.type === TYPE.DARK;
        // StatusBar.setBarStyle(this.isDarkStyle ? 'light-content' : 'dark-content'); // 测试过的机型都有效：华为荣耀V9，红米Note4X，小米Mix2
        // if (Platform.OS == 'android') {
        //     StatusBar.setTranslucent(true); // 测试过的机型几乎都无效：华为荣耀V9，红米Note4X，小米Mix2
        // }
        const leftIcons = this.props.left;
        const rightIcons = this.props.right;
        leftIcons.length < rightIcons.length && leftIcons.push({}); // 补位空白
        leftIcons.length > rightIcons.length && rightIcons.unshift({});
        let containerHeight = StatusBar.currentHeight || 0;
        containerHeight += this.props.subtitle ? navigationBarHeightFat : navigationBarHeightThin;
        const backgroundColor = this.props.backgroundColor
            ? this.props.backgroundColor
            : (this.isDarkStyle ? '#000000' : '#ffffff');
        // StatusBar.setBackgroundColor(backgroundColor); // 仅对某些机型有效：华为荣耀V9
        const containerStyle = {
            backgroundColor,
            height: containerHeight
        }

        const subtitleColor = {
            color: this.isDarkStyle ? darkSubtitleColor : lightSubtitleColor
        }
        return (
            <SafeAreaView style={[styles.container, containerStyle, { paddingTop: StatusBar.currentHeight }]}>
                <StatusBar
                    translucent={true}
                    animated={true}
                    hidden={false}
                    backgroundColor={'transparent'}
                    barStyle={this.isDarkStyle ? 'light-content' : 'dark-content'}
                />
                <View style={{ height: navigationBarHeightThin, flexDirection: 'row', alignItems: 'center' }}>
                    {this.renderIcons(leftIcons, true)}
                    {this.renderTitle()}
                    {this.renderIcons(rightIcons, false)}
                </View>
                {this.props.subtitle
                    ? <Text
                        numberOfLines={1}
                        style={[styles.subtitle, subtitleColor]}
                        onPress={this.props.onPressTitle}
                    >
                        {this.props.subtitle}
                    </Text>
                    : null
                }
            </SafeAreaView>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        width,
        paddingHorizontal,
    },
    titleContainer: {
        flex: 1,
        alignSelf: 'stretch',
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
    },
    title: {
        fontSize: 17,
        // lineHeight: 22,
        textAlignVertical: 'center',
        textAlign: 'center',
    },
    subtitle: {
        marginTop: -10,
        fontSize: 12,
        lineHeight: 17,
        textAlignVertical: 'center',
        textAlign: 'center',
    },
    dot: {
        position: "absolute",
        width: 8,
        height: 8,
        backgroundColor: "red",
        borderRadius: 4
    }
});